package com.xan.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import sun.reflect.generics.tree.ReturnType;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by xueal on 2017/10/19.
 */

public class PlayerDAO {
    private static final Logger logger = Logger.getLogger(PlayerDAO.class.getName());
    private static SessionFactory sessionFactory;

//    private Session session;
//    private Transaction transaction;

    static {
        logger.setLevel(Level.ALL);
        try {
            Configuration config = new Configuration().configure();
            sessionFactory = config.buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return sessionFactory.openSession();
    }

    public static void addPlayer(){
//        Session session=HibernateSessionFactory.getSession();
//        Query query=session.createQuery("from Goods");//hql查询语句保存到query中
//        query.setFirstResult((pageIndex-1)*pageSize).setMaxResults(pageSize);//按照页面显示数据的最大数进行分页设置
//        List<BookEntity> list=query.list();
//        session.close();
//        return list;


//        //2. 创建服务注册对象
//        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//        //3. 创建会话工厂对象
//        sessionFactory = config.buildSessionFactory(serviceRegistry);
//        //4. 会话对象
//        session = sessionFactory.openSession();
//        //5. 开启事务
//        transaction = session.beginTransaction();
        Session session = getSession();

        try {
            Transaction transaction = session.beginTransaction();
            //1. 创建配置对象
    //        Configuration config = new Configuration().configure("/WEB-INF/hibernate.cfg.xml");
    //        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
    //                .configure()
    //                .build();
    //        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
    //                .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build();
    //        sessionFactory = metadata.getSessionFactoryBuilder().build();
    //        // 会话对象
    //        session = sessionFactory.openSession();
    //        // 开启事务
//            transaction = session.beginTransaction();


            //6. 生成专业对象
            PlayerEntity playerEntity = new PlayerEntity();
            playerEntity.setId(UUID.randomUUID().toString());
            playerEntity.setName("xan");
            playerEntity.setRegisterTime(new Timestamp(new Date().getTime()));
            playerEntity.setMoney(100);

            //7. 保存对象进入数据库
            session.save(playerEntity);

            //8. 提交事务
            transaction.commit();
            //9. 关闭会话
//            session.close();
            //10. 关闭会话工厂
//            sessionFactory.close();
//            session.getTransaction().commit();
//下面的代码是IntelliJ IDEA自动生成的，适用于Hibernate4.x,5.x不再可用，执行会报错。
//            System.out.println("querying all the managed entities...");
//            Map<String, ClassMetadata>  map = (Map<String, ClassMetadata>) ourSessionFactory.getAllClassMetadata();
//            for(String entityName : map.keySet()){
//                SessionFactoryImpl sfImpl = (SessionFactoryImpl) ourSessionFactory;
//                String tableName = ((AbstractEntityPersister)sfImpl.getEntityPersister(entityName)).getTableName();
//                System.out.println(entityName + "\t" + tableName);
//            }
//            final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
//            for (Object key : metadataMap.keySet()) {
//                final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
//                final String entityName = classMetadata.getEntityName();
//                final Query query = session.createQuery("from " + entityName);
//                System.out.println("executing: " + query.getQueryString());
//                for (Object o : query.list()) {
//                    System.out.println("  " + o);
//                }
//            }
        } catch (Exception e) {
            Transaction transaction = session.getTransaction();
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    public static List<PlayerEntity> getPlayers(){
        Session session = getSession();
        String hql = "from PlayerEntity";

        List<PlayerEntity> listPlayer = null;
        try {
            Query<PlayerEntity> query = session.createQuery(hql, PlayerEntity.class);
            listPlayer = query.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return listPlayer;
    }

    public static PlayerEntity getPlayer(String playerUUID){
        Session session = getSession();
        String sql = "select * from Player where UUID=" + playerUUID;

        PlayerEntity playerEntity = null;
        try {
            NativeQuery<PlayerEntity> query = session.createNativeQuery(sql, PlayerEntity.class);
            List<PlayerEntity> list = query.getResultList();
            assert list.size() == 1;
            playerEntity = list.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return playerEntity;
    }
}